package by.onlinernews.settings;

import java.io.File;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.v4.preference.PreferenceFragment;
import android.util.Log;
import by.onlinernews.database.DB;
import by.onlinernews.loader.ServiceLoad;
import by.onlinernews.newslist.MainActivity;
import by.onlinernews_0_1.R;

public class SettingsFragment extends PreferenceFragment {
	SharedPreferences sp;
	Boolean showPictures, loadComments;
	int rowsLimit, picsLimit;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.settings);
		sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
		showPictures = sp.getBoolean("chb_pic", false);
		rowsLimit = sp.getInt("rows_limit_seekBar", 300);
		picsLimit = sp.getInt("pic_limit_seekBar", 300);
	}

	@Override
	public void onDestroy() {
		for (int i = 0; i < DB.DB_TABLE.length; i++) {
			if (sp.getInt("rows_limit_seekBar", 300) < rowsLimit)
				DB.checkRowsCountLimit(i, getActivity());
			if (showPictures != sp.getBoolean("chb_pic", false)) {
				getActivity().sendBroadcast(
						new Intent(MainActivity.BROADCAST_ACTION_MAIN)
								.putExtra("flag", MainActivity.STATUS_REFRESH)
								.putExtra("page", i));
				getActivity().sendBroadcast(
						new Intent(MainActivity.BROADCAST_ACTION_MAIN)
								.putExtra("flag", MainActivity.STATUS_FINISH)
								.putExtra("page", i));
			}
		}

		if (sp.getInt("pic_limit_seekBar", 300) < picsLimit) {
			if (Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {
				File sdPath = Environment.getExternalStorageDirectory();
				sdPath = new File(sdPath.getAbsolutePath() + "/"
						+ "OnlinerPictures");
				ServiceLoad.checkPicsLimit(sdPath, getActivity());
			}
		}

		Log.d("pref", "chb_pic = " + sp.getBoolean("chb_pic", false));
		Log.d("pref", "chb_pic_load = " + sp.getBoolean("chb_pic_load", false));

		super.onDestroy();
	}
}
